iT邦幫忙

2023 iThome 鐵人賽

DAY 12
0
Software Development

LELECOCODE 每一天系列 第 12

Day 12 : Leetcode 小挑戰,30 Days of JavaScript

  • 分享至 

  • xImage
  •  

Day 12: Add Two Promises

Given two promises promise1 and promise2, return a new promise. promise1 and promise2 will both resolve with a number. The returned promise should resolve with the sum of the two numbers.

var addTwoPromises = async function(promise1, promise2) {
    
};

Example 1:
Input:
promise1 = new Promise(resolve => setTimeout(() => resolve(2), 20)),
promise2 = new Promise(resolve => setTimeout(() => resolve(5), 60))
Output: 7
Explanation: The two input promises resolve with the values of 2 and 5 respectively. The returned promise should resolve with a value of 2 + 5 = 7. The time the returned promise resolves is not judged for this problem.

Example 2:
Input:
promise1 = new Promise(resolve => setTimeout(() => resolve(10), 50)),
promise2 = new Promise(resolve => setTimeout(() => resolve(-12), 30))
Output: -2
Explanation: The two input promises resolve with the values of 10 and -12 respectively. The returned promise should resolve with a value of 10 + -12 = -2.


var addTwoPromises = async function(promise1, promise2) {
    const [v1, v2] = await Promise.all([promise1, promise2])

    return v1 + v2;
};

// Runtime  64ms
// Beats 30.69%of users with JavaScript

// Memory  41.83MB
// Beats 73.14%of users with JavaScript
var addTwoPromises = async function(promise1, promise2) {
    let sum = 0;
    sum += await promise1;
    sum += await promise2;
    return Promise.resolve(sum);
};

// Runtime  56ms
// Beats 74.75%of users with JavaScript

// Memory  41.97MB
// Beats 61.78%of users with JavaScript

上一篇
Day 11 : Leetcode 小挑戰,30 Days of JavaScript
下一篇
Day 13 : Leetcode 小挑戰,30 Days of JavaScript
系列文
LELECOCODE 每一天30
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言